/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import path from 'path';

import fse from 'fs-extra';

import { HVIGOR_USER_HOME } from '../../../common/const/path-const.js';
import { getHvigorUserHomeCacheDir } from '../../../common/util/hvigor-user-home.js';

const JAVA_DAEMON_CACHE_FILE = 'java-daemon.json';

export function writeJavaDaemonInfo2CacheFile(data: any) {
  const daemonCacheDir = path.resolve(HVIGOR_USER_HOME, 'daemon', 'cache');
  fse.ensureDirSync(daemonCacheDir);
  const javaDaemonCacheFile = path.join(daemonCacheDir, JAVA_DAEMON_CACHE_FILE);
  fse.writeFileSync(javaDaemonCacheFile, JSON.stringify(data));
}

export function readJavaDaemonInfoFromCacheFile(): any | undefined {
  const daemonCacheFile = path.resolve(HVIGOR_USER_HOME, 'daemon', 'cache', JAVA_DAEMON_CACHE_FILE);
  if (fse.existsSync(daemonCacheFile)) {
    try {
      const text = fse.readFileSync(daemonCacheFile).toString();
      return JSON.parse(text);
    } catch (e) {
      return undefined;
    }
  }
  return undefined;
}

export function writeSecretKeyFile(secretKey: string) {
  const daemonCacheDir = path.join(getHvigorUserHomeCacheDir(), 'daemon', 'cache');
  fse.ensureDirSync(daemonCacheDir);
  const secretKeyFile = path.join(daemonCacheDir, 'key.txt');
  fse.writeFileSync(secretKeyFile, secretKey);
}